package com.cet.billingjob.controller;

import lombok.RequiredArgsConstructor;
import org.springframework.batch.core.*;
import org.springframework.batch.core.launch.JobLauncher;
import org.springframework.batch.core.repository.JobExecutionAlreadyRunningException;
import org.springframework.batch.core.repository.JobInstanceAlreadyCompleteException;
import org.springframework.batch.core.repository.JobRestartException;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author 30952
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/job")
public class JobLaunchController {

    private final Job job;

    private final JobLauncher jobLauncher;

    @PostMapping("/launch")
    public Object launchJob() {
        JobParameters jobParameters = new JobParametersBuilder()
            .addString("input.file", "D:\\projects\\cet-practice\\spirng-test\\batch\\billing-job\\input\\billing-2023-03.csv")
            .addString("output.file", "D:\\projects\\cet-practice\\spirng-test\\batch\\billing-job\\staging\\billing-report-2023-03.csv")
            .addJobParameter("data.year", 2023, Integer.class)
            .addJobParameter("data.month", 3, Integer.class)
            .addString("skip.file", "D:\\projects\\cet-practice\\spirng-test\\batch\\billing-job\\staging\\billing-data-skip-2023-03.csv")
            .toJobParameters();
        try {
            JobExecution jobExecution = jobLauncher.run(job, jobParameters);
            return jobExecution.getExitStatus();
        } catch (JobExecutionAlreadyRunningException | JobRestartException | JobInstanceAlreadyCompleteException |
                 JobParametersInvalidException e) {
            throw new RuntimeException(e);
        }
    }
}
